﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;

using CE.Image;
using CE.User;
using CE.Mail;

using CE.Database;

public partial class user_Attendance : System.Web.UI.Page
{
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "100"
            && Session[CE.Global.General.UserId].ToString() != "1499") //Broker 2 is Supervisor
        {
            btnSubmit.Enabled = false;
            ddlAgent.Enabled = false;
            btnDelete.Enabled = false;
            btnNew.Enabled = false;
        }

        if (!Page.IsPostBack)
        {
            LoadAgentList();

            lblAdminName.Text = Session[CE.Global.General.UserName].ToString();

            int _cryr = dateTimeNow.Year;
            int _styr = 2012;
            for (int _year = _cryr; _year >= _styr; _year--)
            {
                ddlFromYear.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
                ddlToYear.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
            }

            ddlFromYear.Text = dateTimeNow.Year.ToString("0000");
            ddlFromMonth.Text = dateTimeNow.Month.ToString("00");
            ddlFromMonth_SelectedIndexChanged(sender, e);
            ddlFromDay.Text = dateTimeNow.Day.ToString("00");

            ddlToYear.Text = dateTimeNow.Year.ToString("0000");
            ddlToMonth.Text = dateTimeNow.Month.ToString("00");
            ddlToMonth_SelectedIndexChanged(sender, e);
            ddlToDay.Text = dateTimeNow.Day.ToString("00");

            CalculateTotalDays();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("attendance");

        DateTime _dateFrom = new DateTime(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlFromMonth.Text), Convert.ToInt32(ddlFromDay.Text));
        DateTime _dateTo = new DateTime(Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlToMonth.Text), Convert.ToInt32(ddlToDay.Text));

        if (_dateTo.CompareTo(_dateFrom) >= 0 && Page.IsValid)
        {
            MyDatabase _db = new MyDatabase();

            SortedList _spara = new SortedList();
            _spara.Add("@AttID", lblAttID.Text);
            _spara.Add("@AgentID", ddlAgent.Text);
            _spara.Add("@AdminID", Session[CE.Global.General.UserId].ToString());
            _spara.Add("@AttType", ddlAttType.Text);
            _spara.Add("@LeaveDayPart", ddlDayPart.Text);


            _spara.Add("@DateFrom", _dateFrom);
            _spara.Add("@DateTo", _dateTo);
            _spara.Add("@Remark", Server.HtmlEncode(txtRemark.Text));

            int _attID = _db.ExecuteNonSqlSP("sprocCXCRMAgentAttendanceInsertUpdateSingleItem", _spara);

            if (_attID > 0)
            {
                lblMessage.Text = "Updated successfully.";
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblAttID.Text = _attID.ToString();

                ClearText();
            }
            else
            {
                lblMessage.Text = "Failed to update.";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }

            grvAttendance.DataBind();
        }
        else
        {
            lblMessage.Text = "Invalid dates.";
            lblMessage.ForeColor = System.Drawing.Color.Red;
        }
    }

    private void ClearText()
    {
        ddlAttType.SelectedIndex = 0;
        ddlDayPart.SelectedIndex = 0;
        txtRemark.Text = string.Empty;
        lblAttID.Text = "0";

        ddlFromDay.Text = dateTimeNow.Day.ToString("00");
        ddlFromMonth.Text = dateTimeNow.Month.ToString("00");
        ddlFromYear.Text = dateTimeNow.Year.ToString("0000");
        ddlToDay.Text = dateTimeNow.Day.ToString("00");
        ddlToMonth.Text = dateTimeNow.Month.ToString("00");
        ddlToYear.Text = dateTimeNow.Year.ToString("0000");

        lblMessage.Text = string.Empty;
        CalculateTotalDays();
        btnDelete.Enabled = false;
    }

    private void LoadAgentList()
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";

            _dt = _db.GetDataTable(_spName);
            ddlAgent.Items.Clear();
            if (_dt != null && _dt.Rows.Count > 0)
            {
                ddlAgent.DataSource = _dt;
                ddlAgent.DataTextField = "FULLNAME";
                ddlAgent.DataValueField = "CEID";
                ddlAgent.DataBind();
            }
        }
        catch (Exception Ex)
        {
        }
    }

    protected void grvAttendance_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearText();

        try
        {
            if (grvAttendance.SelectedIndex >= 0)
            {
                DataKey _dataKey = grvAttendance.SelectedDataKey;

                int _attID = Convert.ToInt32(_dataKey[0]);

                MyDatabase _db = new MyDatabase();
                DataTable _dt = new DataTable("tblList");
                string _spName = "[sprocCXCRMAgentAttendanceSelectSigleItem]";

                SortedList _spara = new SortedList();
                _spara.Add("@AttID", _attID);

                _dt = _db.GetDataTableBySP(_spName, _spara);

                ClearText();

                if (_dt != null && _dt.Rows.Count > 0)
                {
                    lblAttID.Text = _attID.ToString();
                    ddlAgent.Text = _dt.Rows[0]["AgentID"].ToString();

                    ddlAttType.Text = _dt.Rows[0]["AttType"].ToString();
                    ddlDayPart.Text = _dt.Rows[0]["LeaveDayPart"].ToString();

                    DateTime _dateFrom = Convert.ToDateTime(_dt.Rows[0]["DateFrom"].ToString());
                    DateTime _dateTo = Convert.ToDateTime(_dt.Rows[0]["DateTo"].ToString());

                    ddlFromDay.Text = _dateFrom.Day.ToString("00");
                    ddlFromMonth.Text = _dateFrom.Month.ToString("00");
                    ddlFromYear.Text = _dateFrom.Year.ToString("0000");

                    ddlToDay.Text = _dateTo.Day.ToString("00");
                    ddlToMonth.Text = _dateTo.Month.ToString("00");
                    ddlToYear.Text = _dateTo.Year.ToString("0000");

                    txtRemark.Text = _dt.Rows[0]["Remark"].ToString();
                    CalculateTotalDays();
                    btnDelete.Enabled = true;
                }
                else
                {
                    lblMessage.Text = "Failed to load detail.";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        catch (Exception Ex)
        {
            lblMessage.Text = Ex.Message;
            lblMessage.ForeColor = System.Drawing.Color.Red;
        }

    }

    protected void ddlAgent_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClearText();
    }

    private void ShowItem()
    {

    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblAttID.Text) > 0)
        {
            MyDatabase _db = new MyDatabase();
            Int32 _attID = Convert.ToInt32(lblAttID.Text);
            string _spName = "[sprocCXCRMAgentAttendanceDeleteSigleItem]";

            SortedList _spara = new SortedList();
            _spara.Add("@AttID", _attID);

            int _affRow = _db.ExecuteNonSqlSP(_spName, _spara);

            if (_affRow > 0)
            {
                ClearText();
                grvAttendance.DataBind();
                lblMessage.Text = "Deteled successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        ClearText();
    }

    protected void ddlFromMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlFromDay.Items.Clear();

        string strDate = string.Empty;
        DateTime _testDate = dateTimeNow;

        for (int i = 1; i <= 31; i++)
        {
            strDate = i.ToString() + "/" + ddlFromMonth.SelectedItem.Text + "/" + ddlFromYear.Text;

            if (DateTime.TryParse(strDate, out _testDate))
            {
                ddlFromDay.Items.Add(new ListItem(_testDate.ToString("dd - dddd"), _testDate.ToString("dd")));
            }
        }
    }

    protected void ddlToMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlToDay.Items.Clear();

        string strDate = string.Empty;
        DateTime _testDate = dateTimeNow;

        for (int i = 1; i <= 31; i++)
        {
            strDate = i.ToString() + "/" + ddlToMonth.SelectedItem.Text + "/" + ddlToYear.Text;

            if (DateTime.TryParse(strDate, out _testDate))
            {
                ddlToDay.Items.Add(new ListItem(_testDate.ToString("dd - dddd"), _testDate.ToString("dd")));
            }
        }
    }

    protected void ddlFromDay_SelectedIndexChanged(object sender, EventArgs e)
    {
        CalculateTotalDays();
    }

    private void CalculateTotalDays()
    {
        DateTime _dateFrom = new DateTime(Convert.ToInt32(ddlFromYear.Text), Convert.ToInt32(ddlFromMonth.Text), Convert.ToInt32(ddlFromDay.Text));
        DateTime _dateTo = new DateTime(Convert.ToInt32(ddlToYear.Text), Convert.ToInt32(ddlToMonth.Text), Convert.ToInt32(ddlToDay.Text));

        if (_dateTo.CompareTo(_dateFrom) < 0)
        {
            lblTotalDays.Text = "Invalid dates.";
        }
        else
        {
            double _totalDays = (_dateTo - _dateFrom).TotalDays;

            if (_totalDays < 0)
            {
                lblTotalDays.Text = "";
            }

            if (_totalDays >= 0)
            {
                lblTotalDays.Text = (_totalDays + 1d).ToString();
                lblTotalDays.Text += " - " + ddlDayPart.SelectedItem.Text + "  ";
            }
        }
    }

    protected void ddlToDay_SelectedIndexChanged(object sender, EventArgs e)
    {
        CalculateTotalDays();
    }

    protected void ddlDayPart_SelectedIndexChanged(object sender, EventArgs e)
    {
        CalculateTotalDays();
    }
}
